package com.epusn.rewa.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.util.StringUtils;

public class EncryptoUtils {

	public static Map<String,String> keyStroe;

	public static Map<String, String> getKeyStroe() {
		return keyStroe;
	}

	/**
	 * 通过公钥获取私钥
	 * @param publicKey
	 * @return
	 */
	public static String getPrivateKey(String publicKey) {
		 String privateKey = keyStroe.get(publicKey);
		 if(StringUtils.isEmpty(privateKey)) {
			 return null;
		 }
		 return privateKey;
	}
	
	/**
	 * 获取公钥，且keyStroe中只有1个非对称密钥对，如果每次get都生成，没必要且内存会越来越多
	 * 没有就生成
	 * @return
	 */
	public static String getPublicKey() {
		Map<String, Object> genKeyPair = null;
		try {
			if(keyStroe == null || keyStroe.size() !=1) {
				keyStroe = new HashMap<String,String>();
				genKeyPair = RSAUtils.genKeyPair();
				keyStroe.put(new String(RSAUtils.getPublicKey(genKeyPair)), new String(RSAUtils.getPrivateKey(genKeyPair)));
			}
			Set<String> keySet = keyStroe.keySet();
			return keySet.stream().findFirst().get();
		}catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
}
